package com.hongtech.tiny.modules.app.interceptor;

import com.hongtech.tiny.common.exception.CustomException;
import com.hongtech.tiny.common.response.ResultCode;
import com.hongtech.tiny.modules.app.annotation.Login;
import com.hongtech.tiny.modules.app.utils.AppJwtUtils;
import com.hongtech.tiny.modules.knowledge.entity.UserEntity;
import com.hongtech.tiny.modules.knowledge.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * APP权限(Token)验证拦截器验证APP端接口登录
 */
@Component
public class AppAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Resource
    private AppJwtUtils appJwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
        Login annotation = null;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }
        if (annotation == null) {
            return true;
        }
        if (appJwtUtils.getAppHeader() == null) {
            throw new CustomException("请求头参数配置错误！");
        }
        // 获取包含在请求头或者参数中的token信息
        String token = req.getHeader(appJwtUtils.getAppHeader());
        if (StringUtils.isBlank(token)) {
            token = req.getParameter(appJwtUtils.getAppHeader());
        }
        // 获取凭证为空
        if (StringUtils.isBlank(token)) {
            throw new CustomException(ResultCode.UNAUTHORIZED);
        }
        // token验证
        String mobile = appJwtUtils.getMobileFromToken(token);
        if(StringUtils.isBlank(mobile)) {
            throw new CustomException(ResultCode.UNAUTHORIZED);
        }
        UserEntity userEntity = userService.getUserInfoByMobile(mobile);
        if(!appJwtUtils.validateToken(token, userEntity)) {
            throw new CustomException(ResultCode.UNAUTHORIZED);
        }
        return true;
    }

}
